package com.article.lock;

import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Administrator on 2017/5/17.
 */
public abstract class ZookeeperAbstractLock implements Lock {
    private static final Logger log = LoggerFactory.getLogger(ZookeeperAbstractLock.class);
    private static String zkAddress = "120.24.159.173:2181";

    protected static String path = "/lock";

    protected ZkClient zkClient = new ZkClient(zkAddress);

    //阻塞时获取锁
    @Override
    public void getLock() {
        if (tryLock()) {
            System.out.println(Thread.currentThread().getName() + "get lock ！");
            log.info(Thread.currentThread().getName() + "get lock ！");
        } else {
            waitForLock();
            getLock();
        }
    }

    public abstract void waitForLock();

    public abstract boolean tryLock();

    @Override
    public void unLock() {
        zkClient.close();
    }
}
